import json
from openai import OpenAI
import os
import time

def load_questions(file_path):
    """根据文件中的空行加载分组的问题"""
    with open(file_path, "r", encoding='utf-8') as file:
        content = file.read()
    groups = [g.strip() for g in content.split('\n\n') if g.strip()]
    grouped_questions = []
    for group in groups:
        questions = [q.strip() for q in group.split('\n') if q.strip()]
        grouped_questions.append(questions)
    return grouped_questions

def generate_answer(question, context=None):
    client = OpenAI(
        api_key=os.getenv("OPENAI_API_KEY"),  # 请在此处替换为你的 OpenAI API Key
        base_url="https://api.moonshot.cn/v1",
    )

    system_prompt = """
你是 Kimi，由 Moonshot AI 提供的人工智能助手。你会为用户提供安全、有帮助、准确的回答。同时，你回答要简洁准确。
"""

    messages = [
        {"role": "system", "content": system_prompt},
    ]

    if context:
        for qa in context:
            messages.append({"role": "user", "content": qa["question"]})
            messages.append({"role": "assistant", "content": qa["answer"]})

    messages.append({"role": "user", "content": question})

    retry_delay = 5  # 初始重试延迟时间为5秒
    max_retries = 5  # 最大重试次数
    for attempt in range(max_retries):
        try:
            completion = client.chat.completions.create(
                model="moonshot-v1-8k",
                messages=messages,
                temperature=0.3,
            )
            answer = completion.choices[0].message.content.strip()
            time.sleep(3)  # 根据您的速率限制调整等待时间
            return answer
        except Exception as e:
            error_message = str(e)
            if "Error code: 429" in error_message:
                print(f"请求失败: {error_message}. 将在 {retry_delay} 秒后重试... (尝试 {attempt + 1}/{max_retries})")
                time.sleep(retry_delay)
                retry_delay *= 2  # 指数退避策略
            else:
                print(f"请求失败: {error_message}")
                break
    return "由于多次错误，未能生成回答。"

def main():
    questions_file = "questions.txt"
    output_file = "answers.json"

    grouped_questions = load_questions(questions_file)

    output = {
        "sessions": []
    }

    for session_id, questions in enumerate(grouped_questions):
        session = {
            "sessionID": session_id,
            "chatTurns": {}
        }
        context = []
        for turn_id, question in enumerate(questions):
            answer = generate_answer(question, context)
            session["chatTurns"][str(turn_id)] = {
                "question": question,
                "answer": answer
            }
            # 将当前的问答对添加到上下文中
            context.append({"question": question, "answer": answer})
            # 添加延迟以避免触发速率限制
            time.sleep(15)  # 增加等待时间以避免达到速率限制
        output["sessions"].append(session)

    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(output, f, ensure_ascii=False, indent=4)

if __name__ == "__main__":
    main()






